import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/UserLocationModelPage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class OtherUserListPage extends StatefulWidget {
  final bool isSend;
  OtherUserListPage(this.isSend, {Key key}) : super(key: key);

  @override
  _OtherUserListPageState createState() => _OtherUserListPageState();
}

class _OtherUserListPageState extends State<OtherUserListPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page = 1;
  List<LocationModel> cellArr = [];

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    upLoadData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    page = page + 1;
    upLoadData();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  void upLoadData() {
    DioUtils.postHttp(
      context,
      widget.isSend ? "goodsuser/send_address" : "goodsuser/recive_address",
      parameters: {
        "token": getData("token"),
        "type": "2",
        "page": page.toString(),
      },
      onSuccess: (t) {
        print(t);

        LocationListModel model = LocationListModel.fromJson(t);
        if (model.code == 1) {
          if (mounted) {
            setState(() {
              List<LocationModel> arr = model.data;
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Text textLabel01(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(30),
      ),
    );
  }

  Text textLabel02(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF666666),
        fontSize: setFontSize(24),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(context, "常用联系人"),
      body: Container(
        child: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: WaterDropHeader(),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus mode) {
              Widget body;
              if (mode == LoadStatus.idle) {
                body = Text("上拉加载");
              } else if (mode == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (mode == LoadStatus.failed) {
                body = Text("加载失败！点击重试！");
              } else if (mode == LoadStatus.canLoading) {
                body = Text("松手,加载更多!");
              } else {
                body = Text("没有更多数据了!");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: cellArr == null || cellArr.length == 0
              ? Container()
              : ListView.builder(
                  itemCount: cellArr.length,
                  itemBuilder: _listItemBuilder,
                ),
        ),
      ),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return Container(
      color: Color(0xFFEDEDED),
      padding: EdgeInsets.only(top: index == 0 ? setHeight(10) : setHeight(1)),
      child: InkWell(
        onTap: () {
          LocationModel model = cellArr[index];
          Navigator.pop(context, model);
        },
        child: Container(
          padding: EdgeInsets.fromLTRB(
            setWidth(30),
            setHeight(40),
            setWidth(30),
            setHeight(40),
          ),
          color: Colors.white,
          child: Row(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: textLabel01(
                              "${cellArr[index].realname}   ${cellArr[index].mobile}"),
                        ),
                        SizedBox(width: 8),
                        cellArr[index].isDefault == 2
                            ? Container()
                            : Image.asset(
                                widget.isSend
                                    ? "images/LocationTyepImage01.png"
                                    : "images/LocationTyepImage02.png",
                                width: setWidth(120),
                              ),
                      ],
                    ),
                    textLabel02(
                        cellArr[index].address + cellArr[index].buildingNumber),
                  ],
                ),
              ),
              InkWell(
                child: Image.asset(
                  "images/MainMoreImage.png",
                  height: setHeight(60),
                ),
                onTap: () {
                  print("object");
                  showView(context, index);
                },
              )
            ],
          ),
        ),
      ),
    );
  }

  void showView(BuildContext context, int index) {
    showModalBottomSheet(
      context: context,
      // backgroundColor: Colors.green,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      enableDrag: false, //设置不能拖拽关闭
      isDismissible: true, //设置不能点击消失
      isScrollControlled: true,
      builder: (BuildContext context) {
        return Container(
          height: setHeight(400),
          // padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Color(0xFFF2F2F2),
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15)),
          ),
          // color: Colors.white,
          child: Column(
            children: <Widget>[
              InkWell(
                child: Container(
                  // color: Colors.red,
                  alignment: Alignment.center,
                  height: setHeight(120),
                  child: Text(
                    // widget.isSend ? "默认发货" : "默认收货",
                    "设置默认",
                    style: TextStyle(
                      color: Color(0xFF222222),
                      fontSize: setFontSize(32),
                    ),
                  ),
                ),
                onTap: () {
                  print("object");
                  if (cellArr[index].isDefault == 1) {
                    showToast(widget.isSend ? "已是默认发货" : "已是默认收货");
                    return;
                  }
                  showBtn(1, index);
                },
              ),
              Container(
                color: Color(0xFFD4D4D4),
                height: 1,
                // width: screenWidth,
              ),
              InkWell(
                child: Container(
                  // color: Colors.red,
                  alignment: Alignment.center,
                  height: setHeight(120),
                  child: Text(
                    "删除",
                    style: TextStyle(
                      color: Color(0xFF222222),
                      fontSize: setFontSize(32),
                    ),
                  ),
                ),
                onTap: () {
                  print("object");
                  showBtn(2, index);
                },
              ),
              Container(
                color: Color(0xFFD4D4D4),
                height: 10,
                // width: screenWidth,
              ),
              InkWell(
                child: Container(
                  // color: Colors.red,
                  alignment: Alignment.center,
                  height: setHeight(120),
                  child: Text(
                    "取消",
                    style: TextStyle(
                      color: Color(0xFF222222),
                      fontSize: setFontSize(32),
                    ),
                  ),
                ),
                onTap: () {
                  print("object");
                  showBtn(3, index);
                },
              ),
            ],
          ),
        );
      },
    ).then((val) {
      print(val);
    });
  }

  void showBtn(int type, int index) {
    if (type == 3) {
      Navigator.pop(context);
    } else {
      DioUtils.postHttp(
        context,
        widget.isSend
            ? "goodsuser/config_send_address"
            : "goodsuser/config_recive_address",
        parameters: {
          "token": getData("token"),
          "type": type.toString(),
          "id": cellArr[index].id.toString(),
        },
        onSuccess: (t) {
          MainModel model = MainModel.fromJson(t);
          if (model.code == 1) {
            Navigator.pop(context);
            if (type == 2) {
              _onRefresh();
            } else {
              LocationModel model = cellArr[index];
              Navigator.pop(context, model);
            }
          }
        },
        onError: (error) {
          print(error);
        },
      );
    }
  }
}
